package stack;

/**
 * @author niann
 * @description 栈 基于链表实现
 * @since 2024/8/28 下午3:01
 **/
public class Stack<E> implements StackLink<E> {

    private final Node<E> head=new Node<E>();
    private int size;


    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0 ;
    }

    @Override
    public void clear() {
        head.next=null;
        size=0;
    }

    @Override
    public void push(E e) {
        var node = this.head;
        while (node.next!=null){
            node=node.next;
        }
        var node2 = new Node<E>();
        node2.data=e;
        node.next=node2;
        size++;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            throw new RuntimeException("stark is null");
        }
        var node = this.head;
        var prev=new Node<E>();
        while (node.next!=null){
            prev=node;
            node=node.next;
        }
        prev.next=null;
        size--;
        return node.data;
    }

    class Node<E>{
        E data;
        Node<E> next;
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        s.append("[");
        var node = this.head;
        while (node.next!=null){
            node=node.next;
            s.append(node.data).append(",");
        }
        if (size!=0){
            s.delete(s.length()-1,s.length());
        }
        s.append("]");
        return s.toString();
    }
}
